package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.User;
import com.example.electricbicycle.po.Vehicle;
import com.example.electricbicycle.service.PurchaseService;
import com.example.electricbicycle.service.PurchaseServiceImpl;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

@WebServlet("/vehicle/*")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2,  // 2MB
        maxFileSize = 1024 * 1024 * 10,       // 10MB
        maxRequestSize = 1024 * 1024 * 50     // 50MB
)
public class VehicleServlet extends HttpServlet {

    private PurchaseService purchaseService = new PurchaseServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getPathInfo();
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        // 验证用户登录和角色权限（业务员）
        if (currentUser == null || currentUser.getRole() != 0) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        try {
            if (action == null) {
                listVehicles(request, response);
                return;
            }

            switch (action) {
                case "/list":
                    listVehicles(request, response);
                    break;
                case "/new":
                    showNewForm(request, response);
                    break;
                case "/edit":
                    showEditForm(request, response);
                    break;
                case "/view":
                    viewVehicle(request, response);
                    break;
                case "/delete":
                    deleteVehicle(request, response);
                    break;
                default:
                    listVehicles(request, response);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("errorMessage", "系统错误：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/vehicle/list");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getPathInfo();
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || currentUser.getRole() != 0) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        try {
            switch (action) {
                case "/save":
                    saveVehicle(request, response);
                    break;
                case "/update":
                    updateVehicle(request, response);
                    break;
                default:
                    listVehicles(request, response);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("errorMessage", "操作失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/vehicle/list");
        }
    }

    private void listVehicles(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Vehicle> vehicles = purchaseService.getAllVehicles();
        request.setAttribute("vehicles", vehicles);
        System.out.println( vehicles);
        request.getRequestDispatcher("/salesman/vehiclelist.jsp").forward(request, response);
    }

    private void showNewForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/salesman/vehicleform.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Vehicle vehicle = purchaseService.getVehicleById(id);
        if (vehicle != null) {
            request.setAttribute("vehicle", vehicle);
            request.getRequestDispatcher("/salesman/vehicleform.jsp").forward(request, response);
        } else {
            request.getSession().setAttribute("errorMessage", "车辆信息不存在");
            response.sendRedirect(request.getContextPath() + "/vehicle/list");
        }
    }

    private void viewVehicle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Vehicle vehicle = purchaseService.getVehicleById(id);
        if (vehicle != null) {
            request.setAttribute("vehicle", vehicle);
            request.getRequestDispatcher("/salesman/vehicleview.jsp").forward(request, response);
        } else {
            request.getSession().setAttribute("errorMessage", "车辆信息不存在");
            response.sendRedirect(request.getContextPath() + "/vehicle/list");
        }
    }

    private void deleteVehicle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));

        if (purchaseService.deleteVehicle(id)) {
            request.getSession().setAttribute("successMessage", "车辆删除成功！");
        } else {
            request.getSession().setAttribute("errorMessage", "车辆删除失败，该车辆可能已被使用！");
        }

        response.sendRedirect(request.getContextPath() + "/vehicle/list");
    }

    private void saveVehicle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        // 创建车辆对象
        Vehicle vehicle = new Vehicle();
        vehicle.setBrand(request.getParameter("brand"));
        vehicle.setModel(request.getParameter("model"));
        vehicle.setColor(request.getParameter("color"));
        vehicle.setPrice(Double.parseDouble(request.getParameter("price")));
        vehicle.setProductionYear(Integer.parseInt(request.getParameter("productionYear")));

        System.out.println("vehicle:" + vehicle.getBrand()+ vehicle.getModel()+ vehicle.getColor()+ vehicle.getPrice()+ vehicle.getProductionYear());

        // 处理图片上传
        Part filePart = request.getPart("pic");
        String fileName = getFileName(filePart);

        if (fileName != null && !fileName.isEmpty()) {
            // 保存文件到服务器
            String savePath = getServletContext().getRealPath("/images/vehicles");
            // 确保目录存在
            File saveDir = new File(savePath);
            if (!saveDir.exists()) saveDir.mkdirs();
            filePart.write(savePath + File.separator + fileName);
            vehicle.setPic(fileName);
        } else {
            // 使用默认图片
            vehicle.setPic("default-vehicle.jpg");
        }

        // 调用服务层保存车辆
        if (purchaseService.createVehicle(vehicle)) {
            request.getSession().setAttribute("successMessage", "车辆添加成功！");
            response.sendRedirect(request.getContextPath() + "/vehicle/list");
            return;
        } else {
            request.getSession().setAttribute("errorMessage", "车辆添加失败，请重试！");
        }

        request.getRequestDispatcher("/salesman/vehicleform.jsp").forward(request, response);
    }

    private void updateVehicle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");


        int id = Integer.parseInt(request.getParameter("id"));
        Vehicle existingVehicle = purchaseService.getVehicleById(id);

        if (existingVehicle != null) {
            // 更新车辆信息
            existingVehicle.setBrand(request.getParameter("brand"));
            existingVehicle.setModel(request.getParameter("model"));
            existingVehicle.setColor(request.getParameter("color"));
            existingVehicle.setPrice(Double.parseDouble(request.getParameter("price")));
            existingVehicle.setProductionYear(Integer.parseInt(request.getParameter("productionYear")));

            // 处理图片上传 - 仅当用户选择了新图片时更新
            Part filePart = request.getPart("pic");
            String fileName = getFileName(filePart);
            if (fileName != null && !fileName.isEmpty()) {
                String savePath = getServletContext().getRealPath("/images/vehicles");
                // 确保目录存在
                File saveDir = new File(savePath);
                if (!saveDir.exists()) saveDir.mkdirs();
                filePart.write(savePath + File.separator + fileName);
                existingVehicle.setPic(fileName);
            }
            // 如果没有上传新图片，则保留原有图片

            // 调用服务层更新车辆
            if (purchaseService.updateVehicle(existingVehicle)) {
                request.getSession().setAttribute("successMessage", "车辆更新成功！");
                response.sendRedirect(request.getContextPath() + "/vehicle/list");
                return;
            } else {
                request.getSession().setAttribute("errorMessage", "车辆更新失败，请重试！");
            }
        } else {
            request.getSession().setAttribute("errorMessage", "车辆信息不存在");
        }

        response.sendRedirect(request.getContextPath() + "/vehicle/list");
    }

    // 从Part中获取文件名
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                String name = token.substring(token.indexOf('=') + 2, token.length() - 1);
                // 处理文件名，避免路径问题
                return new File(name).getName();
            }
        }
        return "";
    }
}